
package com.study.module.datasource.aspect;


import com.study.module.datasource.annotation.DataSource;
import com.study.module.datasource.config.DynamicContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 多数据源，切面处理类(只能拦截实现类,不能拦截接口)
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect {

    @Pointcut("@annotation(com.study.module.datasource.annotation.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        DataSource dataSource = getDataSource(point);
        if (Objects.nonNull(dataSource)) {
            DynamicContextHolder.set(dataSource.value());
        }
        try {
            return point.proceed();
        } finally {
            DynamicContextHolder.clear();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    private DataSource getDataSource(ProceedingJoinPoint point) {
        //获取被拦截的方法
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取方法上的DataSource注解
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        //如果方法上没有,在获取方法所在类上是有含有该注解
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}